package gatperdut.chato.core.item.inventory;

import gatperdut.chato.core.ChatoServer;
import gatperdut.chato.core.item.ItemController;
import gatperdut.chato.model.Chato.Constant.WearLoc;
import gatperdut.chato.model.Chato.Item.EntityInventorySlot;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SlotsController {

    private final ChatoServer chatoServer;

    private final Map<WearLoc, ItemController> wearLocToItemController = new HashMap<WearLoc, ItemController>();

    private final Map<ItemController, WearLoc> itemControllerToWearLoc = new HashMap<ItemController, WearLoc>();

    private final Map<WearLoc, EntityInventorySlot> wearLocToSlot = new HashMap<WearLoc, EntityInventorySlot>();

    public SlotsController( ChatoServer chatoServer, List<EntityInventorySlot> slots ) {
        this.chatoServer = chatoServer;
        ItemController ic;
        for ( EntityInventorySlot eis : slots ) {
            if ( eis.getItem() != null ) {
                ic = getChatoServer().getItemHandler().getItemToController().get( eis.getItem() );
                getWearLocToItemController().put( eis.getWearLoc(), ic );
                getItemControllerToWearLoc().put( ic, eis.getWearLoc() );
            }
            getWearLocToSlot().put( eis.getWearLoc(), eis );
        }
    }

    public void removeItem( ItemController ic ) {
        getWearLocToItemController().remove( getItemControllerToWearLoc().get( ic ) );
        getWearLocToSlot().get( getItemControllerToWearLoc().get( ic ) ).setItem( null );
        getItemControllerToWearLoc().remove( ic );
    }

    public void setItem( WearLoc wearLoc, ItemController ic ) {
        if ( getItemController( wearLoc ) != null ) {
            throw new IllegalArgumentException( "Overwriting item controller in wear location." );
        }
        getWearLocToItemController().put( wearLoc, ic );
        getItemControllerToWearLoc().put( ic, wearLoc );
        getWearLocToSlot().get( wearLoc ).setItem( ic.getItem() );
    }

    public void clearReferences() {
        wearLocToItemController.clear();
        itemControllerToWearLoc.clear();
    }

    public ItemController getItemController( WearLoc wearLoc ) {
        return getWearLocToItemController().get( wearLoc );
    }

    public ChatoServer getChatoServer() {
        return chatoServer;
    }

    public Map<WearLoc, ItemController> getWearLocToItemController() {
        return wearLocToItemController;
    }

    public Map<ItemController, WearLoc> getItemControllerToWearLoc() {
        return itemControllerToWearLoc;
    }

    public Map<WearLoc, EntityInventorySlot> getWearLocToSlot() {
        return wearLocToSlot;
    }

    public boolean isWearLocFree( WearLoc wearLoc ) {
        return getWearLocToItemController().get( wearLoc ) == null;
    }

}
